#pragma once
#include <functional>
#include <iostream>
#include <unordered_map>
#include<ctime>
using namespace std;
using task_t = function<void()>;
static int num = 0;
void Sql()
{
   cout << "我是数据库同步任务...,pid: " << getpid()<< endl;
}
void DownLoad()
{
   cout << "我是下载任务..,pid: " << getpid() << endl;
}
void Log()
{
   cout << "我是日志任务..,pid: " << getpid() <<  endl;
}
class TaskManager
{
public:
   TaskManager()
   {
      srand(time(nullptr));
      InsertTask(DownLoad);
      InsertTask(Log);
      InsertTask(Sql); 
   }
   ~TaskManager()
   {}
   // 插入任务
   void InsertTask(task_t t)
   {
      tasks[num++] = t;
   }
   // 执行任务
   void Excute(int number)
   {
      if (tasks.find(number) == tasks.end())
         return;
      tasks[number]();
   }
   int SelectTask()//选择任务
   {
      return rand() % num;
   }

 

private:
   unordered_map<int, task_t> tasks;
};

TaskManager tM;

void Worker()
{
   while (true)
   {
      int cmd = 0;
      int n = ::read(0, &cmd, sizeof(cmd));
      if (n == sizeof(cmd))
         tM.Excute(cmd);
      else if (n == 0)
      {
         cout << "pid: "<<getpid() << " quit... "<<endl;
         break; //break之后直接exit
      }
      else // n > 0
      {

      }
   }
}
